import React, { useEffect, useRef, useState } from "react";
import styles from "./Index.module.css";
import { Avatar, CenterPopup, Toast } from "antd-mobile";
import instance from "../../../api/request";
import { useNavigate, useParams } from "react-router-dom";
import dayjs from "dayjs";
import { Input } from "antd-mobile";

function Index() {
  const nav = useNavigate();
  const [xiang, setXiang] = useState([]);
  const { sickCircleId } = useParams();
  //默认收藏为取消
  const [shou, setShou] = useState(false);

  //圆角弹出层
  const [visible, setVisible] = useState(false);

  //评论列表
  const [pl, setPl] = useState([]);
  const [page, setPage] = useState(1);
  const [count] = useState(5);
  const [hasMore, setHasMore] = useState(true);
  const [loading, setLoading] = useState(false);
  const loadMoreRef = useRef(null);

  // 拉取评论列表，单独封装，便于发布后主动刷新
  const fetchComments = () => {
    instance
      .get("/api/user/sickCircle/v1/findSickCircleCommentList", {
        params: {
          sickCircleId: sickCircleId,
          page: page,
          count: count,
        },
      })
      .then((res) => {
        console.log(res, "======评论");
        // setPl(res.data.result)
        const pl = res.data.result;
        setPl((prev) => (page === 1 ? pl : [...prev, ...pl]));
        if (Array.isArray(pl) && pl.length < count) setHasMore(false);
      })
      .finally(() => setLoading(false));
  };
  
  //评论列表接口渲染
  useEffect(() => {
    fetchComments();
  }, [sickCircleId, page, count]);

  //评论输入框
  const [value, setValue] = useState("");

  //发布评论
  const fabup = (e) => {
    // 仅在按下 Enter 时提交，其它按键直接返回
    if (e && e.key && e.key !== "Enter") return;

    // 使用输入框受控值 value，做最简单的非空校验
    const text = (value || "").trim();
    if (!text) {
      Toast.show({ icon: "fail", content: "请输入评论内容" });
      return;
    }

    instance
      .post("/api/user/sickCircle/verify/v1/publishComment", null, {
        params: {
          sickCircleId: sickCircleId,
          content: text,
        },
      })
      .then((res) => {
        console.log(res, "====发布评论");
        Toast.show({ icon: "success", content: "评论成功" });
        setValue(""); // 清空输入框
        // 重新拉取最新评论列表，避免必须刷新页面
        fetchComments();
        // 同步增加详情里的评论数展示
        setXiang((prev) => ({
          ...prev,
          commentNum: (prev?.commentNum || 0) + 1,
        }));
      });
  };
  // const fabup = (e) => {

  //   //回车事件
  //   if (e && e.key && e.key !== "Enter") return;
  //   //非空校验
  //   const text = (value || "").trim();
  //   if (!text) {
  //     Toast.show({ icon: "fail", content: "请输入评论内容" });
  //     return;
  //   }
  //   //调取评论接口
  //   instance
  //     .post("/user/sickCircle/verify/v1/publishComment", null, {
  //       params: {
  //         sickCircleId: sickCircleId,
  //         content: text,
  //       },
  //     })
  //     .then((res) => {
  //       console.log(res, "====发布评论");
  //       Toast.show({ icon: "fail", content: "评论成功" });
  //       setValue("");
  //       //刷新评论列表
  //       fetchComments();
  //       //评论数自增
  //       setXiang((prev) => ({
  //         ...prev,
  //         commentNum: (prev?.commentNum || 0) + 1,
  //       }));
  //     });
  // };

  //收藏接口

  const getshou = () => {
    if (shou === false) {
      instance
        .post("/api/user/verify/v1/addUserSickCollection", null, {
          params: {
            sickCircleId: sickCircleId,
          },
        })
        .then((res) => {
          console.log(res, "====收藏");
          setShou(true);
          Toast.show({
            icon: "success",
            content: "收藏成功",
          });
          setXiang((prev) => ({
            ...prev,
            collectionNum: (prev?.collectionNum || 0) + 1,
          }));
        });
    } else {
      instance
        .delete("/api/user/verify/v1/cancelSickCollection", {
          params: {
            sickCircleId: sickCircleId,
          },
        })
        .then((res) => {
          console.log(res, "====删除收藏");
          setShou(false);
          Toast.show({
            icon: "success",
            content: "取消收藏",
          });
          setXiang((prev) => ({
            ...prev,
            collectionNum: (prev?.collectionNum || 0) - 1,
          }));
        });
    }
  };

  //病友圈详情接口
  const getxiang = () => {
    instance
      .get("/api/user/sickCircle/v1/findSickCircleInfo", {
        params: {
          sickCircleId: sickCircleId,
        },
      })
      .then((res) => {
        console.log(res);
        setXiang(res.data.result);
      });
  };

  useEffect(() => {
    getxiang();
  }, [sickCircleId]);

  return (
    <div className={styles.xiangzong}>
      <div className={styles.heard}>
        <div className={styles.wen} onClick={() => nav("/person")}>
          <Avatar src="" style={{ "--border-radius": "50%" }} />
        </div>

        <div className={styles.wenzi}>
          <h2>{xiang.title}</h2>
        </div>

        <div className={styles.icon}>
          <img src="/heil.png" alt="" />
        </div>
      </div>

      <div className={styles.footer}>
        <p className={`${styles.zi} ${styles.author}`}>{xiang.authorUserId}</p>

        <div className={styles.xianglie}>
          <span>
            <b>[症状]</b>
            <p>{xiang.disease}</p>
          </span>

          <span className={styles.mt17}>
            <b>[科室]</b>
            <p>{xiang.department}</p>
          </span>

          <span className={styles.mt17}>
            <b>[症状详情]</b>
            <p>{xiang.detail}</p>
          </span>

          <span>
            <b>[治疗经历]</b>
            <p>{xiang.treatmentProcess}</p>
          </span>

          <span>
            <b>[相关图片]</b>
            <p>
              {/* <img
                src="https://ts4.tc.mm.bing.net/th/id/OIP-C.4N-OsQiieTh-anWO1p5qRAHaHa?w=80&h=80&c=1&bgcl=f4404a&r=0&o=7&dpr=1.5&pid=ImgRC&rm=3"
                alt=""
              /> */}
            </p>
          </span>

          <span>
            <div className={styles.shouc}>
              <div>
                {shou === true ? (
                  <img src="/sfinish.png" alt="" onClick={() => getshou()} />
                ) : (
                  <img src="/shouc.png" alt="" onClick={() => getshou()} />
                )}{" "}
                {xiang.collectionNum}
              </div>

              <div>
                <img
                  src="/xiaoxi.png"
                  alt=""
                  onClick={() => setVisible(true)}
                />
                <div className={styles.shoucs}>{xiang.commentNum}</div>
              </div>
            </div>
          </span>
        </div>
      </div>

      <CenterPopup
        visible={visible}
        onMaskClick={() => {
          setVisible(false);
        }}
        maskStyle={{ background: "rgba(0,0,0,0.35)" }}
        bodyStyle={{ background: "transparent", boxShadow: "none" }}
      >
        <div className={styles.plPopupWrap}>
          {pl.map((item) => {
            return (
              <div
                key={item.commentId}
                className={styles.content}
                style={{
                  display: "flex",
                  padding: "10px 0 0 10px",
                }}
              >
                {/* 用户头像 */}
                <div onClick={() => nav(`/bingxin`)}>
                  <Avatar
                    style={{
                      borderRadius: "50%",
                      width: "35px",
                      height: "35px",
                      marginRight: "10px",
                    }}
                    src={item.headPic}
                  />
                </div>

                <div
                  style={{
                    minWidth: "150px",
                    minHeight: "20px",
                    maxWidth: "70vw",
                    padding: "10px",
                    borderRadius: "5px",
                    background: "#fff",
                  }}
                >
                  {/* 昵称 发表时间 */}
                  <p>
                    <span style={{ color: "#ccc" }}>{item.nickName}</span>&emsp;
                  </p>
                  {/* 评论内容 */}
                  <div>{item.content}</div>
                  <p>
                    <span style={{ color: "#ccc" }}>
                      {dayjs(item.createTime).format("DD/MM/YYYY")}
                    </span>

                    <span style={{ marginLeft: "15px" }}>
                      <img src="/zan.png" alt="" />
                    </span>
                    <span style={{ marginLeft: "15px" }}>
                      <img src="/dao.png" alt="" />
                    </span>
                  </p>
                </div>
              </div>
            );
          })}

          <div className={styles.wenb}>
            <button
              className={styles.btn}
              type="button"
              onClick={() => setVisible(false)}
            >
              X
            </button>

            <div className={styles.bubble}>
              <Input
                className={styles.input}
                placeholder="在此留下高见吧！！"
                value={value}
                onChange={(val) => setValue(val)}
                onKeyDown={fabup}
              />
            </div>
          </div>
        </div>
      </CenterPopup>


      <div className={styles.pl}>
        <div className={styles.wenz}>
          <div>
            <img src="/wen.jpg" alt="" />
          </div>

          <div className={styles.zi}>被采纳的建议</div>
        </div>

        <div></div>
      </div>
    </div>
  );
}

export default Index;
